package com.spring.hx.security;

import com.spring.hx.config.GlobalConfig;
import com.spring.hx.entity.User;
import com.spring.hx.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class RedisTokenManager implements TokenManager{

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    private RedisUtils redisUtils;
    private GlobalConfig globalConfig;
    @Autowired
    public void setGlobalConfig(GlobalConfig globalConfig) {
        this.globalConfig = globalConfig;
    }




    @Override
    public String getToken(User userInfo) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        String token_format=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.set(token_format,userInfo,globalConfig.getTokenExistSecs());
        return token;
    }

    @Override
    public boolean refreshUserToken(String token) {
        token=String.format(Constants.TOKEN_FORMAT,token);
        if(redisUtils.exists(token)){
            return redisUtils.setExpireTime(token, globalConfig.getTokenExistSecs());
        }
        return false;
    }

    @Override
    public void loginOff(String token) {
        token=String.format(Constants.TOKEN_FORMAT,token);
        redisUtils.remove(token);
    }

    @Override
    public User getUserInfoByToken(String token) {
        token=String.format(Constants.TOKEN_FORMAT,token);
        if(redisUtils.exists(token)){
            return (User )redisUtils.get(token);
        }
        return null;
    }
}
